import React, { Component, Fragment } from 'react';
import TodoItem from './TodoItem';
import axios from 'axios';
import './style.css';

class TodoList extends Component {

  constructor(props) {
    super(props);
    // 当组件的state或者props发生改变的时候，render()函数就会重新执行
    this.state = {
      inputValue: '',
      list: []
    };
    this.handleInputChange = this.handleInputChange.bind(this);
    this.handleEnterClick = this.handleEnterClick.bind(this);
    this.handleBtnClick = this.handleBtnClick.bind(this);
    this.handleItemDelete = this.handleItemDelete.bind(this);
  }

  render() {
    return (
      <Fragment>
        <div>
          <label htmlFor="insertArea">输入内容</label>
          <input
            id="insertArea"
            className="input"
            value={this.state.inputValue}
            onChange={this.handleInputChange}
            onKeyDown={this.handleEnterClick}
          />
          <button onClick={this.handleBtnClick}>提交</button>
        </div>
        <ul ref = {(ul) => {this.ul = ul}}>{this.getTodoItem()}</ul>
      </Fragment>
    )
  }  

  componentDidMount() {
    axios.get('http://127.0.0.1:8080/three.json').then((data)=>{console.log(data)});
  }

  getTodoItem() {
    return this.state.list.map((item, index) => {
      return (
        <TodoItem
          key={index}               // index不是确定唯一值，对性能有所消耗
          content={item}
          index={index}
          deleteItem={this.handleItemDelete}
        />
      )
    })
  }

  handleInputChange(e) {
    const value = e.target.value;
    this.setState(() => ({
        inputValue: value
    }));    
  }
  handleEnterClick(e) {
    if (e.keyCode === 13) {
      this.handleBtnClick()
    };
  }
  handleBtnClick() {    
    if (this.state.inputValue) {
      this.setState((prevSate) => ({
        list: [...prevSate.list, prevSate.inputValue],
        inputValue: ''
      }), () => {
        // console.log(this.ul.querySelectorAll('div').length)
      });      
    }
  }
  handleItemDelete(index) {
    // immutable
    // state 不允许我们做任何的改变
    this.setState((prevSate) => {
      const list = [...prevSate.list];
      list.splice(index, 1)
      return {list}      
    });
  }
}

export default TodoList;